'use strict';
	angular.module('customer.customerGroupTree', [])

	.controller('customerGroupTreeCtrl'
			,['$rootScope', '$scope', '$uibModal', 'BizData', '$ocLazyLoad', f])//控制器结束
	function f($rootScope,$scope, $uibModal, BizData, $ocLazyLoad) {
		var common = require('common');
		
  		var Model = this;
		
		//定义页面级别的变量
   		var systemCode = $rootScope.winid; //系统代码
		var billType = "KHFL";
		var billTypeName = "客户分类";


		
		/**
		name:bizData#onNewCreateParam
		description: <b>[回调型事件]</b>业务新增数据创建新增参数事件，可以增加和修改用户自定义的参数
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"param" : {justep.Request.ActionParam} 新增参数对象,
			"defaultValues" : array - 新增行的默认值数组 ，数组的长度决定新增行数，数组中的对象是列的默认值
				defaultValues格式：
					[
						{列名:默认值,...},
						{列名:默认值,...},
						...
					]
		}
		</xmp>	
		@see justep.XData#newData
		@see justep.Request.ActionParam
		*/
		Model.dataMasterNewCreateParam = function(event) {
			event.param = {"billType": billType};
		}
   		

   		/**
   		name:bizData#onBeforeDelete
   		description: <b>[回调型事件]</b>业务数据删除前
   		@param {object} event 它的结构如下:<br/>
   		{
   			"source":组件的js对象
   			,"cancel":可修改	，设置为true后中断当前delete动作
   			,"deleteIDList":删除的行Id数组
   		}
   		*/
   		Model.dataMasterBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
   		}
   		/**
   		name:bizData#onAfterDelete
   		description: <b>[回调型事件]</b>业务数据删除后
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   			"source" : 组件的js对象,
   			"deleteIDList" : 删除的行Id数组
   		}
   		</xmp>	
   		*/
   		Model.dataMasterAfterDelete = function(event) {
//   			alert('删除之后！')
   		}

   		
   		
   		/**
   		name:bizData#onIndexChanging
   		description: <b>[回调型事件]</b>行记录变化中
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   			"source" : 组件的js对象,
   			"rowID" : 行Id,
   			"rowIndex" : 行索引,
   			"originalRowID" : 原行Id,
   			"originalRowIndex" : 原行索引
   		}
   		</xmp>	
   		*/
   		Model.dataMasterIndexChanging = function(event){
   			
   		};
   		
   		
   		/**
   		name:bizData#onIndexChanged
   		description: <b>[回调型事件]</b>行记录变化
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   		"source" : 组件的js对象,
   		"rowID" : 行Id,
   		"rowIndex" : 行索引
   		}
   		</xmp>	
   		*/
   		Model.dataMasterIndexChanged = function(event) {
   			
  		}
   		
   		/**
   		name:bizData#onDataChanged
   		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   		"source" : 组件的js对象,
   		"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
   		"selfChanged" : 是否自身变化，false：从data触发的变化,
   		"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
   		}
   		</xmp>	
   		*/
   		Model.dataMasterDataChanged = function(event) {
   			
   		}
   		
   		/**
   		name:bizData#onValueChanged
   		description: <b>[回调型事件]</b>数据变化
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   		"source" : 组件的js对象,
   		"column" : 关系,
   		"rowIndex" : 行索引,
   		"value" : 新值,
   		"originalValue" : 旧值
   		}
   		</xmp>	
   		*/
   		//输入值变化，监视input的输入，ng-change
   		Model.dataMasterValueChanged = function(event) {
   			
			if(event.column=='groupLabel'){
				//整合自身全路径名称
				var rowID = event.source.getID(event.rowIndex);
				var fParent = event.source.getValue('fParent',rowID);
				var groupLabel = event.value;
				var groupFullLabel = '';
				if(fParent==null || fParent==''){
					groupFullLabel = groupFullLabel + '' + groupLabel;
				}else{
					groupFullLabel = event.source.getValue('groupFullLabel',fParent) + '/' + groupLabel;
				}
				event.source.setValue('groupFullLabel',groupFullLabel,rowID);
			}
			
			if(event.column=='groupFullLabel'){
				//修改子节点的全路径名称
				var rowID = event.source.getID(event.rowIndex);
				var ids = Model.dataMaster.getChildsIDs(rowID);
				for(var i=0;i<ids.length;i++){
					var groupFullLabel = event.value + '/' + event.source.getValue('groupLabel',ids[i]);
					event.source.setValue('groupFullLabel',groupFullLabel,ids[i]);
				}
			}


			if(event.column=='status'){
				var rowID = event.source.getID(event.rowIndex);
				var ids = Model.dataMaster.getChildsIDs(rowID);
				for(var i=0;i<ids.length;i++){
					event.source.setValue('status',event.value,ids[i]);
				}
			}

			
   		}
   		


   		/**
   		name:bizData#onBeforeNew
   		description: <b>[回调型事件]</b>业务数据新增前
   		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
   		*/
   		Model.dataMasterBeforeNew = function(event) {

   		};
   		
   		
   		/**
   		* name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
   		* 
   		* @param event
   		*            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
   		*/
   		Model.dataMasterAfterNew = function(event){
			
			//创建行后赋值
			event.source.setValue('systemCode',systemCode,event.id);
			event.source.setValue('billType',billType,event.id);
			event.source.setValue('billTypeName',billTypeName,event.id);
			
			
			//整合自身全路径编码
			var fID = event.id;
			var fParent = event.source.getValue('fParent',fID);
			var groupFullID = '';
			if(fParent==null || fParent==''){
				groupFullID = '/' + fID;
			}else{
				groupFullID = event.source.getValue('groupFullID',fParent) + '/' + fID;
				//展开父节点
				Model.dataMaster.expandRow(fParent);
			}
			event.source.setValue('groupFullID',groupFullID,fID);

   		}
   		
   		
		
		///////////////////按钮组开始///////////////////////////////////////////////////
		//新建（跟）
		Model.addRoot = function(){
		//	if(Model.dataMaster.getTotal()<=0){
		//		Model.dataMaster.loadData('');
		//	}
			//树形专用
			var nodeKind = 'nkLeaf';
			var fParent = null;
			var groupFullID = null;
			var nodeLevel = 1;
			var sortNo = null;
			
			fParent = null;
			groupFullID = null;
			nodeLevel = 1;
			var rootCount = Model.dataMaster.getRoots().length;
			sortNo = '/' + common.preZeroFill(rootCount + 1,3);
			
			var options = {
					index : Model.dataMaster.rows.length,
					defaultValues : [
					                 {
						            	 state:'active'
						            	 ,status:'open'
//						            	 ,audit:'active'
						            	 
					                	 ,fParent:fParent
					                	 ,nodeKind:nodeKind
					                	 ,nodeLevel:nodeLevel
					                	 ,sortNo:sortNo
						            	 
						            	 ,billType: billType
						            	 ,orderDate: ':getCurrentDate()'
							             ,employeeNo: ':getCurrentPsmFID()'
								         ,employeeName: ':getCurrentPsmFName()'
							             ,cUsercode: ':getCurrentPersonCode()'
								         ,cUsername: ':getCurrentPersonName()'
									     ,cDatetime: ':getCurrentDateTime()'
										 ,userId: ':getCurrentPersonID()'
										 ,enterpriseNo: ':getCurrentOgnFID()'
										 ,enterpriseName: ':getCurrentOgnLongName()'
										 ,version: 0
						            	 
					                	 }
//					                 ,{sName:'a2',sCode:'b2'}
					                 ]
			};    

			var ids = Model.dataMaster.newData(options);
			//设置全路径ID
//			Model.dataMaster.rows[Model.dataMaster.currentIndex].groupFullID.value = (groupFullID==null?'':groupFullID) + '/' + ids[0];
			
		}
		//新建子节点
		Model.addChild = function(){
			//树形专用
			var nodeKind = 'nkLeaf';
			var fParent = null;
			var groupFullID = null;
			var nodeLevel = 1;
			var sortNo = null;
			
			if(Model.dataMaster.currentIndex== null){return;}
			fParent = Model.dataMaster.currentID;
			var parentIndex = Model.dataMaster.getIndex(fParent);
			groupFullID = Model.dataMaster.rows[Model.dataMaster.currentIndex].groupFullID.value;
			nodeLevel = Model.dataMaster.rows[Model.dataMaster.currentIndex].nodeLevel.value + 1;
			var childCount = Model.dataMaster.getChilds(fParent).length;
			
			sortNo =Model.dataMaster.rows[Model.dataMaster.currentIndex].sortNo.value + '/' + common.preZeroFill(childCount + 1,3);
			
			Model.dataMaster.rows[Model.dataMaster.currentIndex].nodeKind.value = null;			
			
			var childrenCount = Model.dataMaster.getChildren(fParent).length;
			var options = {
					index : parentIndex + childrenCount + 1,
					defaultValues : [
					                 {
						            	 state:'active'
						            	 ,status:'open'
//						            	 ,audit:'active'
						            	 
					                	 ,fParent:fParent
					                	 ,nodeKind:nodeKind
					                	 ,nodeLevel:nodeLevel
					                	 ,sortNo:sortNo
						            	 
						            	 ,billType: billType
						            	 ,orderDate: ':getCurrentDate()'
							             ,employeeNo: ':getCurrentPsmFID()'
								         ,employeeName: ':getCurrentPsmFName()'
							             ,cUsercode: ':getCurrentPersonCode()'
								         ,cUsername: ':getCurrentPersonName()'
									     ,cDatetime: ':getCurrentDateTime()'
										 ,userId: ':getCurrentPersonID()'
										 ,enterpriseNo: ':getCurrentOgnFID()'
										 ,enterpriseName: ':getCurrentOgnLongName()'
										 ,version: 0
						            	 
					                	 }
//					                 ,{sName:'a2',sCode:'b2'}
					                 ]
			};    

			var ids = Model.dataMaster.newData(options);
			//设置全路径ID
//			Model.dataMaster.rows[Model.dataMaster.currentIndex].groupFullID.value = (groupFullID==null?'':groupFullID) + '/' + ids[0];
			//展开父节点
//			Model.dataMaster.expandRow(fParent);
		}
		//新建兄弟节点
		Model.addBrother = function(){
			//树形专用
			var nodeKind = 'nkLeaf';
			var fParent = null;
			var groupFullID = null;
			var nodeLevel = 1;
			var sortNo = null;
			
			if(Model.dataMaster.currentIndex== null){return;}
			fParent =  Model.dataMaster.rows[Model.dataMaster.currentIndex].fParent.value;
			if(fParent==null || fParent==''){return;}
			var parentIndex = Model.dataMaster.getIndex(fParent);
			groupFullID = Model.dataMaster.rows[parentIndex].groupFullID.value;
			nodeLevel = Model.dataMaster.rows[Model.dataMaster.currentIndex].nodeLevel.value;
			var childCount = Model.dataMaster.getChilds(fParent).length;
			sortNo =Model.dataMaster.rows[parentIndex].sortNo.value + '/' + common.preZeroFill(childCount + 1,3);
			
//			Model.dataMaster.rows[Model.dataMaster.currentIndex].nodeKind.value = null;			
			
			var childrenCount = Model.dataMaster.getChildren(fParent).length;
			var options = {
					index : parentIndex + childrenCount + 1,
					defaultValues : [
					                 {
						            	 state:'active'
						            	 ,status:'open'
//						            	 ,audit:'active'
						            	 
					                	 ,fParent:fParent
					                	 ,nodeKind:nodeKind
					                	 ,nodeLevel:nodeLevel
					                	 ,sortNo:sortNo
						            	 
						            	 ,billType: billType
						            	 ,orderDate: ':getCurrentDate()'
							             ,employeeNo: ':getCurrentPsmFID()'
								         ,employeeName: ':getCurrentPsmFName()'
							             ,cUsercode: ':getCurrentPersonCode()'
								         ,cUsername: ':getCurrentPersonName()'
									     ,cDatetime: ':getCurrentDateTime()'
										 ,userId: ':getCurrentPersonID()'
										 ,enterpriseNo: ':getCurrentOgnFID()'
										 ,enterpriseName: ':getCurrentOgnLongName()'
										 ,version: 0
						            	 
					                	 }
//					                 ,{sName:'a2',sCode:'b2'}
					                 ]
			};    

			var ids = Model.dataMaster.newData(options);
			//设置全路径ID
//			Model.dataMaster.rows[Model.dataMaster.currentIndex].groupFullID.value = (groupFullID==null?'':groupFullID) + '/' + ids[0];
			//展开父节点
//			Model.dataMaster.collapseRow(fParent);
//			Model.dataMaster.expandRow(fParent);
		}
		
		//修改
		Model.edit = function(){
			Model.dataMaster.editData();
		}
		
		//保存
		Model.save = function() {
			Model.dataMaster.saveData();
		}
		
		//取消保存
		Model.saveCancel = function() {
			if(Model.dataMaster.userdata.recordState == 'new'){
				Model.dataMaster.loadPageData();
			}else{
				Model.dataMaster.refreshPageData();
			}
			Model.dataMaster.userdata.recordState = 'none';
		}
		
		//直接删除
		Model.remove = function() {
			//console.log('Model.dataMaster.directDeleteMode-->>',Model.dataMaster.directDeleteMode);
			if(Model.dataMaster.directDeleteMode){
				if(Model.dataMaster.deleteData(Model.dataMaster.getCurrentID())==0){
					Model.dataMaster.refreshData();
				}
			}else{
				//console.log('删除-->>',Model.dataMaster.removeData(Model.dataMaster.getCurrentID()));
				var rowID = Model.dataMaster.getCurrentID();
				Model.dataMaster.removeData(rowID);
				Model.dataMaster.editData();
			}
		};
		
		//刷新
		Model.refresh = function() {
			Model.dataMaster.refreshData();
		}
		
		//排序
		Model.sort = function(fParent) {
			var parentID = null;
			if(fParent!='root'){
				parentID = Model.dataMaster.getCurrentID();
			}

			var options = {};
			
			options.recordState = 'none';
			options.parentID = parentID;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/customer/customerGroup/sortView',  
	            controller: 'customerGroupSortCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '排序'; }
                    ,loadCtrl : $ocLazyLoad.load('js/customer/customerGroup/sort')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
				
				//装配参数
				var data = new Object();
				data.parentID = parentID;
				data.ids = returnData;
				
				var response = $.ajax({
		            type: "POST",
		            async : false,
		            url: $rootScope.getProjectName() + "/customer/customerGroup/tree/sort",
		            data: JSON.stringify(data),// "{}",
		            contentType: "application/json; charset=utf-8",
		            dataType: "json",
//		            processData: false,
		            success: function (data) {
		                // Play with returned data in JSON format
		            },
		            error: function (msg) {
//		                alert(msg.responseText);
		            }
		        });

				if (response.readyState == 4 && response.status == 200) {
    				Model.dataMaster.refreshPageData();
    				if(parentID!=null){
    					Model.dataMaster.expandRow(parentID);
    				}
    				return 0;
    			}else{
    				alert('操作失败！')
    				return -1;
    			}
				
				

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		
		//移动
		Model.move = function() {
			var options = {};
			
			options.recordState = 'none';
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/customer/customerGroup/moveView',  
	            controller: 'customerGroupMoveCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/customer/customerGroup/move')
		        }
	        });  

	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
				console.log('returnData-->',returnData);
				
				//新父节点ID
				var newParentID = null;
				if(returnData!=null){
					//移动到顶层
					newParentID = returnData[0].fID;
				}
				console.log('newParentID-->',newParentID);
				
				var dataMaster = Model.dataMaster;
				var rowID = dataMaster.getCurrentID();
				var oldParentID = dataMaster.getValue('fParent',rowID);
				//前后父节点不能相同
				if(newParentID==oldParentID){
					return;
				}
				
				//装配参数
				
				var data = new Object();
				data.rowID = rowID;
				data.oldParentID = oldParentID;
				data.newParentID = newParentID;
				
				var response = $.ajax({
		            type: "POST",
		            async : false,
		            url: $rootScope.getProjectName() + "/customer/customerGroup/tree/move",
		            data: JSON.stringify(data),// "{}",
		            contentType: "application/json; charset=utf-8",
		            dataType: "json",
//		            processData: false,
		            success: function (data) {
		                // Play with returned data in JSON format
		            },
		            error: function (msg) {
//		                alert(msg.responseText);
		            }
		        });

				if (response.readyState == 4 && response.status == 200) {
    				dataMaster.refreshPageData();
    				var index = dataMaster.getIndex(rowID);
    				dataMaster.setCurrentIndex(index);
    				if(newParentID!=null){
    					dataMaster.expandRow(newParentID);
    				}
    				return 0;
    			}else{
    				alert('操作失败！')
    				return -1;
    			}
				
				

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
	        
		};
		
		

		///////////////////按钮组结束///////////////////////////////////////////////////
   		
   		var options = {};
		options.container = Model;
		options.concept = 'FileCustomerGroup';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
   		options.creater = '/customer/customerGroup/tree/create';
   		options.reader = '/customer/customerGroup/tree/query';
   		options.writer = '/customer/customerGroup/tree/save';
   		options.deleter = '/customer/customerGroup/tree/delete';
   		options.idColumnDefine = "fID";
   		options.idColumnName = "fID";
   		options.isTree = true;
   		options.parentRelation = 'fParent';
   		options.nodeKindRelation = 'nodeKind';
   		options.nodeLevelRelation = 'nodeLevel';
   		options.nodeSortRelation = "sortNo";
//   	options.rootFilter = 'FileCustomerGroup.fParent is null';
   		options.pathRelation = 'groupFullID';
   		options.directDeleteMode = false;
   		options.limit = -1;
   		options.orderBy = 'sortNo ASC';


   		options.onIndexChanging = Model.dataMasterIndexChanging;
   		options.onIndexChanged = Model.dataMasterIndexChanged;
   		options.onBeforeNew = Model.dataMasterBeforeNew;
   		options.onAfterNew = Model.dataMasterAfterNew;
   		options.onBeforeDelete = Model.dataMasterBeforeDelete;;
   		options.onAfterDelete = Model.dataMasterAfterDelete;
   		options.onValueChanged = Model.dataMasterValueChanged;
   		options.onDataChanged = Model.dataMasterDataChanged;
		options.onNewCreateParam = Model.dataMasterNewCreateParam;
   		
   		Model.dataMaster = new BizData(options);

//      Model.dataMaster.deregIndex = $scope.$watch('dataMaster.currentIndex',Model.dataMaster.watchCurrentIndex);
//      Model.dataMaster.deregID = $scope.$watch('dataMaster.currentID',Model.dataMaster.watchCurrentID);
   		//监视对象中的所有变动
   		Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
//      Model.dataMaster.deregCollection = $scope.$watch('dataMaster.rows',Model.dataMaster.watchCollection,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
   		//////////////////////////////////////////////

   		Model.dataMaster.filter = "FileCustomerGroup.billType='"+billType+"'";
   		
   		
   		Model.dataMaster.refreshData();

   		
		////////////////////////////////////////////////////////////////////////////////////////

		
	    return Model;

	}	
	
